import whiteList from "./pre-defined/white-list";
import {Next} from "koa";
import { AppCTX } from "../types/koaExtend"
import { decode, TokenPayload } from "../utils/jwt"
import {
  isUndefined
} from "mmb";

export default async (ctx: AppCTX, next: Next) => {
  const reqUrl = ctx.request.url;
  if (whiteList.token.findIndex((item) => reqUrl.startsWith(item)) === -1) {
    // if (ctx.header.token) { // 有token
      
    // }
    try {
      let payload = await decode(ctx.header.token) as TokenPayload
      if (isUndefined(payload.userId)) {
        ctx.throw(401, '4011')
      }
      ctx.userId = payload.userId
      ctx.userOpenId = payload.userOpenId
    } catch (error) {
      console.error('tokenNW err=>', JSON.stringify(error))
      ctx.throw(401, JSON.stringify({
        code: 401,
        message: `token认证失败:${error.message}`
      }))
    }
  }
  await next();
};